<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    @close="handleClose"
  >
    <el-form
      ref="fromRef"
      :model="form"
      :rules="rules"
      :label-width="formLabelWidth"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!initData.id">
        <el-input
          v-model="form.password"
          type="password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.mobile" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from "vue";
import { addUsers, editUsers } from "@/api/user";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const i18n = useI18n();
const fromRef = ref(null);
const dialogVisible = ref(true);
const formLabelWidth = "140px";

let form = reactive({
  username: "",
  password: "",
  email: "",
  mobile: ""
});
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur"
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur"
    }
  ]
});
const emits = defineEmits(["update:modelValue", "updateList"]);
const props = defineProps({
  dialogTitle: {
    type: String,
    required: true
  },
  initData: {
    type: Object,
    required: false,
    default: () => {}
  }
});
watch(
  () => props.initData,
  (value) => {
    form = value;
  },
  { deep: true, immediate: true }
);
const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = () => {
  if (!fromRef.value) return;
  fromRef.value.validate(async (valid) => {
    if (valid) {
      form.id ? await editUsers(form) : await addUsers(form);
      ElMessage({
        message: i18n.t("message.updateSuccess"),
        type: "success"
      });
      emits("updateList");
      handleClose();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style lang="scss"></style>
